package com.zys.sac.core.helper;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.concurrent.TimeUnit;

/**
 * lyy
 * 2022/5/19
 */
@Slf4j
public class RedisTokenManager implements TokenManager {

    @Autowired
    protected RedisTemplate<String, Object> redisTemplate;

    protected long expired;

    public RedisTokenManager(long expired) {
        this.expired = expired;
    }

    @Override
    public String createAndSaveToken(UserDetails userDetails) {
        return this.createAndSaveToken(userDetails, this.expired);
    }

    @Override
    public String createAndSaveToken(UserDetails userDetails, long expired) {
        String token = generateToken(userDetails);
        String cacheKey = token;
        this.redisTemplate.opsForValue().set(cacheKey, userDetails, expired, TimeUnit.SECONDS);
        return token;
    }

    @Override
    public void renewalToken(String token) {
        this.renewalToken(token, this.expired);
    }

    @Override
    public void renewalToken(String token, long expired) {
        String cacheKey = token;
        UserDetails userDetails = (UserDetails) this.redisTemplate.opsForValue().get(cacheKey);
        this.redisTemplate.opsForValue().set(cacheKey, userDetails, expired, TimeUnit.SECONDS);
    }

    @Override
    public UserDetails getUserDetails(String token) {
        String cacheKey = token;
        UserDetails userDetails = (UserDetails) this.redisTemplate.opsForValue().get(cacheKey);
        return userDetails;
    }

    @Override
    public void invalidToken(String token) {
        String cacheKey = token;
        this.redisTemplate.delete(cacheKey);
    }

}
